﻿using System.Collections.ObjectModel;
using System.Linq;
using Atha.Clients.ViewModels;
using Atha.Contracts;
using Atha.Extensions.TestRunTestResults;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;

namespace Atha.Clients.Wpf
{
	public class ClientTestRunner : IClientTestRunner
	{
		public void ExecuteTest(string testLanguage, string testScript, ObservableCollection<TestResultViewModel> testResults)
		{
			var unityContainer = ServiceLocator.Current.GetInstance<IUnityContainer>();

			var testRunContext = unityContainer.Resolve<ITestRunContext<AggregateTestResult>>(
				testLanguage,
				new ParameterOverride("name", testLanguage),
				new ParameterOverride("script", testScript));

			var testRunTestResults = testRunContext.Execute();

			MapResults(testRunTestResults, testResults);
		}

		private static void MapResults(AggregateTestResult testResult, ObservableCollection<TestResultViewModel> targetTestResults)
		{
			targetTestResults.Add(MapResult(testResult));

			var results = testResult.Results.Select(MapResult);

			foreach (var result in results)
				targetTestResults.Add(result);
		}

		private static TestResultViewModel MapResult(ITestRunTestResult testResult)
		{
			var iconPath = (string)null;

			if (testResult.Succeeded())
			{
				iconPath = @"Images/success.png";
			}
			else if (testResult.Failed())
			{
				iconPath = @"Images/failure.png";
			}
			else
			{
				iconPath = @"Images/inconclusive.png";
			}

			return new TestResultViewModel(testResult.Name, iconPath);
		}
	}
}
